package com.value.helper;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;

/**
 * Unibon
 * <p/>
 * Copyright (c) 2012 YouPeng ValueSoft Inc., All rights reserved.
 * <p/>
 * This software is the confidential and proprietary information of
 * ValueSoft Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with ValueSoft.com.
 * <p/>
 * Revision History
 * Date      		Programmer       Notes
 * 2014/6/16   	     libo		     Initial
 * *********************************************************************
 */
public class FtpHelper {
    private String ip = "";
    private String username = "";
    private String password = "";
    FTPClient ftpClient;

    public FtpHelper(String serverIP, String username, String password) {
        this.ip = serverIP;
        this.username = username;
        this.password = password;
    }

    /**
     * 上传文件
     * @param file
     * @param path
     */
    public boolean uploadFile(File file , String path) {
        File file2 = new File(file.getPath());
        try {
            InputStream input = new FileInputStream(file2);
            ftpClient.changeWorkingDirectory(path);
            ftpClient.storeFile(file2.getName(), input);
            input.close();  //关闭输入流
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 上传文件夹
     * @param folder
     * @param path
     */
    public boolean uploadFolder(String folder , String path) {
        File src = new File(folder);
        try {
            path = path + src.getName() + "/";
            this.ftpClient.makeDirectory(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        File[] allFile = src.listFiles();
        for (File file : allFile) {
            if (!file.isDirectory()) {
                String srcName = file.getPath().toString();
                uploadFile(new File(srcName), path);
            }else{
                uploadFolder(file.getPath(),path);
            }
        }
        return true;
    }

    /**
     * 下载文件
     * @param localFile
     * @param remotePath
     * @param remoteName
     * @return
     */
    public File downloadFile(String localFile,String remotePath,String remoteName){
        File file = new File(localFile);
        try {
            ftpClient.changeWorkingDirectory(remotePath);
            FileOutputStream fos = new FileOutputStream(file);
            ftpClient.retrieveFile(remoteName, fos);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public FTPFile[] listAllFiles(String remotePath){
        try {
            FTPFile[] files = ftpClient.listFiles(remotePath);
            return files;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 连接ftp服务器
     * @return
     */
    public boolean connectServer(){
        boolean flag = true;
        ftpClient = new FTPClient();
        try {
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.connect(this.ip);
            ftpClient.login(this.username, this.password);
            int reply = ftpClient.getReplyCode();
            ftpClient.setDataTimeout(120000);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.err.println("FTP server refused connection.");
                // logger.debug("FTP 服务拒绝连接！");
                flag = false;
            }
        } catch (SocketException e) {
            flag = false;
            e.printStackTrace();
            System.err.println("登录ftp服务器 " + ip + " 失败,连接超时！");
        } catch (IOException e) {
            flag = false;
            e.printStackTrace();
            System.err.println("登录ftp服务器 " + ip + " 失败，FTP服务器无法打开！");
        }
        return flag;
    }

    /**
     * 关闭连接
     */
    public void closeConnect() {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
